package self.zhangkang.chart

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import self.zhangkang.chart.data.KLineInfo

/**
 * @author：zhangkang19164
 * created on：2025/3/20 15:10
 * description：
 */
class AvgViewModel(application: Application) : AndroidViewModel(application) {

    private var mCurrentStock: Stock? = null

    private val mAvgLiveData = MutableLiveData<List<KLineInfo>>()
    val avgLiveData: LiveData<List<KLineInfo>> = mAvgLiveData

    fun setStock(stock: Stock?) {
        mCurrentStock = stock
        if (null == stock) {
            clearData()
        } else {
            loadData(stock)
        }
    }

    private fun loadData(stock: Stock) {
        if ("600000" == stock.code && "SH" == stock.codeType) {
            viewModelScope.launch(Dispatchers.IO) {
                getApplication<Application>().assets.open("SH600000.json").bufferedReader().use {
                    val jsonObject = JSONObject(it.readText())
                    val info = jsonObject.getJSONObject("info")
                    val dataList = info.getJSONArray("datas")
                    val preClose = info.getDouble("PC").toFloat()
                    val length = dataList.length()
                    val resultList = mutableListOf<KlineQuote>()
                    repeat(length) { index ->
                        val dataInfo = dataList.getJSONObject(index)
                        val klineQuote = KlineQuote(
                            T = dataInfo.getString("T"),
                            O = dataInfo.getString("O"),
                            C = dataInfo.getString("C"),
                            V = dataInfo.getString("V"),
                            VL = dataInfo.getString("VL"),
                            AM = dataInfo.getString("AM")
                        )
                        resultList.add(klineQuote)
                    }
                    val klineData = resultList.map { klineQuote ->
                        DataTools.kLineQuoteToKLineInfo(
                            klineQuote = klineQuote,
                            preCLosePrice = preClose
                        )
                    }.toMutableList()
                    mAvgLiveData.postValue(klineData)
                }
            }
        }

    }

    private fun clearData() {
        mAvgLiveData.postValue(emptyList())
    }


}